import base64
import cv2
import os
import re
from PIL import Image, ImageFile


def add_img_path(dir_path):
    """指定一个文件夹，获取一个空的图片绝对路径"""
    if os.path.exists(dir_path):
        return os.path.abspath(os.path.join(dir_path, str(len(os.listdir(dir_path)))+".png"))
    else:
        return None


def change_alink(s, path):
    """修改超链接路径"""
    return re.sub(r'<a href=([\s\S]*)><img src=', "<a href="+path + "?img><img src=", s)


def get_str_base64(s):
    """从图片消息中获取base64字符串"""
    return re.findall(r';base64,([\s\S]*)" width=', s)[0]


def copy_img(path, str_base64):
    """将base64字符保存为本地图片"""
    with open(path, "wb") as f:
        f.write(base64.b64decode(str_base64))


def read_img(path):
    """读取本地图片为base64"""
    with open(path, "rb") as f:
        return str(base64.b64encode(f.read()))[2:-1]


def show_img(path):
    """图片查看器"""
    img = cv2.imread(path)
    cv2.namedWindow(path, cv2.WINDOW_NORMAL)
    cv2.imshow(path, img)
    while True:
        if cv2.getWindowProperty(path, 0) == -1:  # 当窗口关闭时为-1，显示时为0
            break
        cv2.waitKey(1)
    cv2.destroyWindow(path)


def compress_image(infile, outfile="", mb=1024, quality=85, k=0.2):  # 通常你只需要修改mb大小
    """不改变图片尺寸压缩到指定大小
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标，KB
    :param k: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址，压缩文件大小
    """

    o_size = os.path.getsize(infile) // 1024  # 函数返回为字节，除1024转为kb（1kb = 1024 bit）
    if o_size <= mb:
        return infile
    if not outfile:
        outfile = infile + "_zip.png"
    ImageFile.LOAD_TRUNCATED_IMAGES = True  # 防止图像被截断而报错
    while o_size > mb:
        im = Image.open(infile)
        x, y = im.size
        out = im.resize((int(x * k), int(y * k)), Image.ANTIALIAS)  # 最后一个参数设置可以提高图片转换后的质量
        try:
            out.save(outfile, quality=quality)  # quality为保存的质量，从1（最差）到95（最好），此时为85
        except Exception as e:
            print(e)
            break
        o_size = os.path.getsize(outfile) // 1024
    return outfile


if __name__ == "__main__":
    path = "../.cache/img_buf/temp.png"
    s = '<a href=file:///D:/FILES/Python/Project/project/PyChat/client/src/error.png><img src="data:file:///D:/FILES/Python/Project/project/PyChat/client/src/error.png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAA4WlDQ1BzUkdCAAAYlWNgYDzNAARMDgwMuXklRUHuTgoRkVEKDEggMbm4gAE3YGRg+HYNRDIwXNYNLGHlx6MWG+AsAloIpD8AsUg6mM3IAmInQdgSIHZ5SUEJkK0DYicXFIHYQBcz8BSFBDkD2T5AtkI6EjsJiZ2SWpwMZOcA2fEIv+XPZ2Cw+MLAwDwRIZY0jYFhezsDg8QdhJjKQgYG/lYGhm2XEWKf/cH+ZRQ7VJJaUQIS8dN3ZChILEoESzODAjQtjYHh03IGBt5IBgbhCwwMXNEQd4ABazEwoEkMJ0IAAHLYNoSjH0ezAAAACXBIWXMAABJ0AAASdAHeZh94AAAU4UlEQVR4nO3dbWxc1ZkH8P9zZubaCU5FAyxK4hk7QDwzTigU6G7Ky1KIoLSEDwsCFaQCJUZadYu0JLsO/bQrbVvJrhJ2Bct+qFNopW21i1hWwrAsLCSUwoJ4aVASz9ghiz2TOEINYSV7SXxn5jz7wWPXScb2vNxzz8y9z+9LpMnMOQ/R+XPu6zkEYQQDkcNdTk9RI6kIPQAuAHEHmFYxowPEqxRTBxM6AKwC5v8EgCkA0wCmiDGtiafBNEWEaRBPgWkawGeaMRZVGN0w4Y4RULLzXxpsZLuAVndg7Yq4E+Ue5lIPCD1gSmI2EJf6XMoRMMZAPArGGFFkzC3S2OWTp/I+1xEoEpAaZda19aio/lNmuoWBWwj4su2alsLA5wS8SsSv6qL6TfrYzJjtmlqJBGQZme72brC+Vmm+lhXdAkaP7ZoaQhgjza9qRW+D1Nvp8dPjtktqZhKQCg7H224tKn0bNF1LhD+xXY9JzHgXit+OavXyhvzMK7braTYSkLJsInodQ20lYCuATbbrseQgA8MEPZzKFd+yXUwzCHVARtfFrmBFWwnYyoTNtutp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BCB4BVwPyfADAFYBrAFDGmNfE0mKaIMA3iKTBNA/hMM8aiCqMbJtwxAkp2/kuD7f8BRD6RUneImbkAAAAASUVORK5CYII=" width="50" height="50" /></a>'
    # data_base64 = get_str_base64(s)
    # print(data_base64)
    # copy_img(path, data_base64)
    # show_img(path)
    print(change_alink(s, "path"))
